package se.recept.kollen.module.extension;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.persist.UnitOfWork;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.ExecutionContext;
import net.sourceforge.stripes.controller.Interceptor;
import net.sourceforge.stripes.controller.Intercepts;
import net.sourceforge.stripes.controller.LifecycleStage;

/**
 *
 * @author jocke
 */
@Intercepts({LifecycleStage.EventHandling})
public class TransactionInterceptor implements Interceptor {

    @Inject
    private Provider<EntityManager> provider;
    
    @Inject private UnitOfWork unitOfWork;

    @Override
    public Resolution intercept(ExecutionContext context) throws Exception {

        final EntityTransaction txn = provider.get().getTransaction();

        if (txn.isActive()) {
            return context.proceed();
        }

        txn.begin();
        Resolution resolution = null;

        try {
            resolution = context.proceed();
            txn.commit();
            return resolution;
        } catch (Exception e) {
            txn.rollback();
            throw new IllegalStateException(e);
        } finally {
            unitOfWork.end();
        }

    }

}
